﻿using UnityEngine;

namespace Assets.XyzCode.Comm
{
    /// <summary>
    /// 灰度处理
    /// </summary>
    [ExecuteInEditMode]
    public class GrayscaleBehav : MonoBehaviour
    {
        /** 着色器 */
        public Shader shader;

        /** 灰度系数 */
        [Range(0, 1)]
        public float scaleVal = 0.5f;

        /** 材质 */
        private Material _material;

        /// <summary>
        /// 获取材质
        /// </summary>
        /// <returns></returns>
        private Material GetMaterial()
        {
            if (null == _material 
             || null != shader)
            {
                _material = new Material(shader);
            }

            return _material;
        }

        /// <summary>
        /// OnRenderImage
        /// </summary>
        /// <param name="srcTexture">源纹理</param>
        /// <param name="dstTexture">目标纹理</param>
        void OnRenderImage(RenderTexture srcTexture, RenderTexture dstTexture)
        {
            Material m = GetMaterial();

            if (null != m)
            {
                m.SetFloat("_Grayscale", scaleVal);
                Graphics.Blit(srcTexture, dstTexture, m);
            }
            else
            {
                Graphics.Blit(srcTexture, dstTexture);
            }
        }
    }
}
